package encoding.CharSet;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class ByteLengthInDiffEncode {

    /**
     * @param args
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
        final String charsetUTF8 = "UTF-8";
        final String charsetUnicode = "Unicode";
        final String charsetGB2312 = "GB2312";

        String chineseString = "你好";
        String englishString = "Hello";

        byte[] a;
        String newStr;

        Properties properties = System.getProperties();
        for (Object key : properties.keySet()) {
            System.out.println(key.toString() + ": " + properties.get(key).toString());
        }

        a = chineseString.getBytes(); // System default encoding
        System.out.println(a.length);

        a = chineseString.getBytes(charsetUTF8);
        System.out.println(a.length);

        a = chineseString.getBytes(charsetUnicode);
        System.out.println(a.length);
        newStr = new String(a);
        System.out.println("Unicode -> System default: " + newStr);
        newStr = new String(a, charsetUnicode);
        System.out.println(newStr);

        a = chineseString.getBytes(charsetGB2312);
        System.out.println(a.length);
        newStr = new String(a, charsetGB2312);
        System.out.println(newStr);
        newStr = new String(a, charsetUTF8);
        System.out.println(newStr);
        
        // There would be 3 invisible chars on tail.
        a = englishString.getBytes(charsetUTF8);
        byte [] b = new byte[a.length + 3];
        System.arraycopy(a, 0, b, 0, a.length);
        System.out.println(new String(b, charsetUTF8));
        
        // it would be crash the sun HotSpot JVM of JDK 1.6.26
        // but it seems that it could not reproduce.
//        byte[] c = new byte[4];
//        System.out.println(new String(c));
    }
}
